<template>
    <div>
        <div style='margin-bottom: 20px;'>
            <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState"
                @finish="onFinish">
                <a-row :gutter="24">
                    <a-col :span="4">
                        <a-form-item name="day_start" label="白天起步价">
                            <a-input v-model:value="formState[`day_start`]" placeholder="请输入 可以使用 >  < 控制大于还是小于"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="4">
                        <a-form-item name="night_start" label="夜间起步价">
                            <a-input v-model:value="formState[`night_start`]"
                                placeholder="请输入 可以使用 >  < 控制大于还是小于"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="4">
                        <a-form-item name="start_free" label="免费公里">
                            <a-input v-model:value="formState[`start_free`]" placeholder="请输入 可以使用 >  < 控制大于还是小于"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="4">
                        <a-form-item name="price" label="超出单价">
                            <a-input v-model:value="formState[`price`]" placeholder="请输入 可以使用 >  < 控制大于还是小于"></a-input>
                        </a-form-item>
                    </a-col>

                    <a-col :span="4">
                        <a-form-item name="traffic_type" label="交通类别">
                            <a-radio-group v-model:value="formState['traffic_type']">
                                <a-radio-button value="">全部</a-radio-button>
                                <a-radio-button value="0">出租/滴滴</a-radio-button>
                                <a-radio-button value="1">公交/地铁</a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>

                </a-row>
                <a-row>
                    <a-col :span="20" style="text-align: left;margin-bottom: -50px;z-index: 100;">
                        <a-button type="primary" @click="adds" v-if="!dis[0] || !dis[1] ">新增</a-button>
                    </a-col>
                    <a-col :span="24" style="text-align: right">
                        <a-button type="primary" html-type="submit">查询</a-button>
                        <a-button style="margin: 0 8px" @click="() => { formRef.resetFields(); onFinish() }">重置</a-button>

                    </a-col>
                </a-row>
            </a-form>
            <a-table bordered :data-source="dataSource" :columns="columns"
                :pagination="{ current, pageSize, total: totalCount }" @change="pageClick">

                <template #bodyCell="{ column, text, record }">

                    <template v-if="column.dataIndex == 'traffic_type'">
                        <a-tag color="purple" v-if="record.traffic_type == 0">出租/滴滴</a-tag>
                        <a-tag color="purple" v-if="record.traffic_type == 1">地铁/公交</a-tag>
                    </template>


                    <template v-if="column.dataIndex === 'operation'">
                        <a-popconfirm :title="'真的要删除吗'" @confirm="deleTraffic(record.uid,record.image,record.dir)">
                            <a :style="{ color: share.color, marginLeft: '15px' }">删除</a>
                        </a-popconfirm>
                        <span :style="{marginLeft: '15px',color:share.color}"
                            @click="showModal(record)">修改</span>
                    </template>
                    <template v-if="column.dataIndex == 'image'">
                        <a-image :width="50" :heigth="50" :src='share.http + `/${record.dir}/${record.image}`' />
                    </template>
                </template>
            </a-table>
        </div>
        <!-- 交通新增 -->
        <a-modal v-model:visible="addModel" title="交通新增" :width="850" @ok="addOk" :destroyOnClose="true">
            <a-form ref="addForm" :model="addFormState">
                <a-form-item label="交通名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model:value="addFormState.name" :maxlength="200" />
                </a-form-item>

                <a-form-item label="白天起步价" name="day_start" :rules="[{ required: true, message: '请输入白天起步价!' }]">
                    <a-input-number v-model:value="addFormState.day_start" :min="1" :max="1000" :width="400"/>
                </a-form-item>
                <a-form-item label="夜间起步价" name="night_start" :rules="[{ required: true, message: '请输入夜间起步价!' }]">
                    <a-input-number v-model:value="addFormState.night_start" :min="1" :max="1000" />
                </a-form-item>
                <a-form-item label="免费公里路程(km)" name="start_free" :rules="[{ required: true, message: '请输入免费公里长度!' }]">
                    <a-input-number v-model:value="addFormState.start_free" :min="1" :max="10000" />
                </a-form-item>
                <a-form-item label="超出公里的单价" name="price" :rules="[{ required: true, message: '请输入免费公里长度!' }]">
                    <a-input-number v-model:value="addFormState.price" :min="1" :max="10000" />
                </a-form-item>
                <a-form-item label="出行方式" name="traffic_type"
                    :rules="[{ required: true, message: '请选择出行方式!' }]">
                    <a-radio-group v-model:value="addFormState.traffic_type" name="traffic_type">
                        <a-radio value="1" v-if="dis[1]==0">公交/地铁</a-radio>
                        <a-radio value="0" v-if="dis[0]==0">滴滴出行</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="项目主图" name="image">
                    <a-upload :fileList="fileListData"  :maxCount="1"
                        list-type="picture-card" :beforeUpload="beforeUp">
                        <div>
                            <plus-outlined />
                            <div style="margin-top: 8px">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <div>摘要说明:</div>
                <a-textarea v-model:value="textData" :rows="3" :cols="120" placeholder="概要说明"/>
            </a-form>
        </a-modal>
        <!-- 交通修改 -->
        <a-modal v-model:visible="setModel" title="交通修改" :width="850" @ok="setOk" :destroyOnClose="true">
            <a-form ref="setForm" :model="setFormState">
                <a-form-item label="交通名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
                    <a-input v-model:value="setFormState.name" :maxlength="200" />
                </a-form-item>

                <a-form-item label="白天起步价" name="day_start" :rules="[{ required: true, message: '请输入白天起步价!' }]">
                    <a-input-number v-model:value="setFormState.day_start" :min="1" :max="1000" :width="400"/>
                </a-form-item>
                <a-form-item label="夜间起步价" name="night_start" :rules="[{ required: true, message: '请输入夜间起步价!' }]">
                    <a-input-number v-model:value="setFormState.night_start" :min="1" :max="1000" />
                </a-form-item>
                <a-form-item label="免费公里路程(km)" name="start_free" :rules="[{ required: true, message: '请输入免费公里长度!' }]">
                    <a-input-number v-model:value="setFormState.start_free" :min="1" :max="10000" />
                </a-form-item>
                <a-form-item label="超出公里的单价" name="price" :rules="[{ required: true, message: '请输入免费公里长度!' }]">
                    <a-input-number v-model:value="setFormState.price" :min="1" :max="10000" />
                </a-form-item>
                <a-form-item label="出行方式" name="traffic_type"
                    :rules="[{ required: true, message: '请选择出行方式!' }]">
                    <a-radio-group v-model:value="setFormState.traffic_type" name="traffic_type">
                        <a-radio value="1" v-if="setFormState.traffic_type==1">公交/地铁</a-radio>
                        <a-radio value="0" v-else-if="setFormState.traffic_type==0">滴滴出行</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="项目主图" name="image">
                    <a-upload :fileList="fileListData"  :maxCount="1"
                        list-type="picture-card" :beforeUpload="beforeUp">
                        <div>
                            <plus-outlined />
                            <div style="margin-top: 8px">Upload</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <div>摘要说明:</div>
                <a-textarea v-model:value="textData" :rows="3" :cols="120" placeholder="概要说明"/>
            </a-form>
        </a-modal>
    </div>
</template>


<script setup>
import { ref, onMounted, reactive } from 'vue'
import {PlusOutlined } from '@ant-design/icons-vue';
import { useUserData } from '../../../stores/userData';
import { useRouter } from 'vue-router';
import share from '../../../util/commnet'
import { message } from 'ant-design-vue';
import { trafficAPI } from '../../../api/traveling'
import { imageAPI } from '../../../api/management';
import {debounce} from 'lodash'
const store = useUserData();
const router = useRouter();



const formRef = ref('');    //搜索数据

const formState = reactive({  //搜素内容
    traffic_type: '',
    day_start: "",
    night_start: '',
    start_free: '',
    price: "",
});
const dataSource = ref([{}]);   //表格数据
const totalCount = ref(0);      //总条
const pageSize = ref(10);       //一页多少条
const current = ref(1);         //当前页
const columns = [{
    title: '交通uid',
    dataIndex: 'uid',
    align: 'center'

}, {
    title: '交通工具',
    dataIndex: 'traffic_name',
    align: 'center'

}, {
    title: "交通图片",
    dataIndex: "image",
    align: 'center',
    width:100
}, {
    title: '交通类型',
    dataIndex: 'traffic_type',
    align: 'center'

}, {
    title: "白天起步价",
    dataIndex: 'day_start',
    align: 'center'

}, {
    title: '夜间起步价',
    dataIndex: 'night_start',
    align: 'center'

}, {
    title: "免费公里数",
    dataIndex: "start_free",
    align: 'center'

}, {
    title: "超出单价",
    dataIndex: "price",
    align: 'center'

}, {
    title: "定价说明",
    dataIndex: "illustrate",
    ellipsis: true,
    width: 250
}, {
    title: '操作',
    dataIndex: 'operation',
    align: 'center'

}];
const dis = ref([]);  //是否禁用新增条件
const onFinish = () => {  //条件查询
    pageClick();
}


const debouncedPageClick = debounce(async (item) => {           //进行防抖
    item ? current.value = item.current : current.value = 1;
    let res = await trafficAPI(`traffic|${formState.traffic_type}|${formState.day_start}|${formState.night_start}|${formState.start_free}|${formState.price}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {

        message.error(res.message);
        return
    }
    dataSource.value = res.data
    totalCount.value = res.total - 0;
    let sel = await trafficAPI(`sel|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    dis.value = sel.data;
}, 300);

const pageClick = (item) => {       //页面变化刷新表格
    debouncedPageClick(item);
};



const deleTraffic = async (uid, image, dir) => {  //点击删除
    console.log(image);
    let res = await trafficAPI(`del|${uid}|${image}|${dir}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message);
        return
    }
    message.success('删除成功')
    pageClick();
}

// 新增-------------------------------------------------------------------------------
const addForm = ref(null)
const fileList = ref('');  //文件保存地
const addFormState = ref({});  //修改时表单的数据
const fileListData = ref([])  //文件展示区
const addModel = ref(false);
const adds = () => {
    fileListData.value = [];
    addModel.value = true;
}
const textData = ref('');
const beforeUp = f=>{               //上传图片前
    fileList.value = f;
    fileListData.value = [{url:URL.createObjectURL(f)}]
    return false;
}
const addOk = ()=>{
    addForm.value.validateFields()
    .then(async res=>{
        let imageEnd;
        if(fileList.value){
            imageEnd = await imageAPI(`trafficADD|${store.data.token}|${store.data.uuid}|${store.data.phone}`,fileList.value);
            if(!imageEnd ||imageEnd.code ==406){
                message.error("账号失效")
                router.replace({name:"login"});
                return
            }else if(imageEnd.code !=200){

                message.error(imageEnd.message);
                return
            }
        }else{
            message.error("请上传一张主图！！")
            return;
        }

        let addtr = await trafficAPI(`add|${res.traffic_type}|${res.day_start}|${res.name}|${res.night_start}|${res.price}|${res.start_free}|${textData.value}|${imageEnd.file}|${store.data.token}|${store.data.uuid}|${store.data.phone}`)
        console.log(addtr);
        if(!addtr ||addtr.code ==406){
            message.error("账号失效")
            router.replace({name:"login"});
            return
        }else if(addtr.code !=200){
            message.error(imageEnd.message);
            return
        }
        
        message.success("新增成功")
        addModel.value = false;
        addFormState.value = {};
        textData.value = '';
        pageClick()
    })
}

// 修改----------------------------------------------------------------------------------------------
const setForm  = ref(null)
const setFormState = ref({})
const setModel = ref(false)
const showModal = (item)=>{
    setFormState.value = {
        name:item.traffic_name,
        day_start:item.day_start,
        night_start:item.night_start,
        start_free:item.start_free,
        price:item.price,
        uid:item.uid,
        traffic_type:item.traffic_type,
        image:item.image
    }
    console.log(setFormState.value);
    fileListData.value = [{ url: `${share.http}/${item.dir}/${item.image}` }]
    textData.value = item.illustrate;
    setModel.value = true;
}
const setOk = async()=>{
    setForm.value.validateFields()
    .then(async res=>{
        let up;
        if(fileList.value){  //当上传了文件
            up = await imageAPI(`trafficSet|${setFormState.value.image}|${store.data.token}|${store.data.uuid}|${store.data.phone}`,fileList.value);   //进行图片上传操作
            if(up.code!=200){   

                message.error(up.message);
                return
            }else{
                setFormState.value.image = up.file;
            }
        }else{          //当没有上传文件
            up = await imageAPI(`trafficNoset|${setFormState.value.image}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
            if(up.code==400){
                message.error(up.message);

                return
            }
        }

        let setSql = await trafficAPI(`set|${setFormState.value.traffic_type}|${setFormState.value.day_start}|${setFormState.value.name}|${setFormState.value.night_start}|${setFormState.value.price}|${setFormState.value.start_free}|${textData.value}|${up.file}|${setFormState.value.uid}|${store.data.token}|${store.data.uuid}|${store.data.phone}`)
        if (!setSql || setSql.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (setSql.code != 200) {

            message.error(res.message);
            return
        }
        message.success('修改成功');
        console.log(setSql);
        setModel.value = false;
        setFormState.value = {};
        textData.value = '';
        pageClick()
    })
}

onMounted(async () => {
    let res = await trafficAPI(`traffic|${formState.traffic_type}|${formState.day_start}|${formState.night_start}|${formState.start_free}|${formState.price}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message);
        return
    }
    dataSource.value = res.data;
    totalCount.value = res.total - 0;
    let sel = await trafficAPI(`sel|${store.data.token}|${store.data.uuid}|${store.data.phone}`);  
    dis.value = sel.data;  
    console.log(dis.value);
})
</script>

<style scoped></style>